<template>
  <container-wrapper :designer="designer"
                     :widget="widget"
                     :index-of-parent-list="indexOfParentList"
                     :parent-widget="parentWidget" :parent-list="parentList"
  >
    <div :class="[selected ? 'selected' : '', customClass]">
      <div class="grid-stack" :id="widget.id" @click.stop="selectWidget(widget)">
      </div>
    </div>
    <teleport v-if="isLoaded" v-for="(item,colIdx) in gridItems" :key="item.id" :to="`#grid-item-${item.id}`">
      <grid-col-widget
        :itemId="item.id"
        :widget="item.widget"
        :designer="designer"
        :parent-list="widget.cols"
        :parent-widget="widget"
        @removeWidget="item.remove"
      />
    </teleport>
  </container-wrapper>
</template>

<script>
import i18n from '@/utils/i18n'
import GridColWidget from '@/components/form-designer/form-widget/container-widget/grid-col-widget'
import containerMixin from '@/components/form-designer/form-widget/container-widget/containerMixin'
import ContainerWrapper from '@/components/form-designer/form-widget/container-widget/container-wrapper'
import refMixinDesign from '@/components/form-designer/refMixinDesign'

import { GridStack } from 'gridstack'

export default {
  name: 'grid-widget',
  componentName: 'ContainerWidget',
  mixins: [i18n, containerMixin, refMixinDesign],
  inject: ['refList'],
  components: {
    ContainerWrapper,
    GridColWidget,
  },
  props: {
    widget: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,
  },
  data() {
    return {
      count: 0,
      info: '',
      grid: null,
      gridItems: [],
      //用来区分是load调用的add还是addWidget调用的add
      isLoad: false,
      isLoaded: false,
    }
  },
  computed: {
    selected() {
      return this.widget.id === this.designer.selectedId
    },

    customClass() {
      return this.widget.options.customClass || ''
    },

  },
  watch: {
    //
  },
  created() {
    this.initRefList()
  },
  mounted() {
    this.grid = GridStack.init({ // DO NOT use grid.value = GridStack.init(), see above
      float: true,
      cellHeight: this.widget.options.colHeight,
      minRow: 1,
      margin: '5px',
    }, document.getElementById(this.widget.id))

    this.grid.on('change', (event, element) => {
      this.saveGridItems()
    })
    this.grid.on('added', (event, items) => {
      if (!this.isLoad) {
        const colWidget = this.designer.addNewColOfGrid(this.widget)
        this.widget.cols.push(colWidget)
        // 渲染到teleport,因为此处如果使用render，会导致gridColWidget中的组件无法获取inject
        this.handleGridItems(items, colWidget)
      } else {
        this.handleGridItems(items)
      }
      this.saveGridItems()
    })
    this.grid.on('removed', (event, items) => {
      items.forEach((item) => {
        this.gridItems.splice(this.gridItems.findIndex(gridItem => item.id === gridItem.id), 1)
        this.widget.cols.splice(this.widget.cols.findIndex(col => item.id === col.id), 1)
      })
      this.saveGridItems()
    })
    if (this.widget.options?.gridItems?.length > 0) {
      this.isLoad = true
      this.grid.load(this.widget.options.gridItems)
    }
  },
  methods: {
    saveGridItems() {
      this.widget.options.gridItems = this.grid.getGridItems().map((item) => {
        return {
          id: item.gridstackNode.id,
          x: item.gridstackNode.x,
          y: item.gridstackNode.y,
          w: item.gridstackNode.w,
          h: item.gridstackNode.h,
        }
      })
      this.designer.emitHistoryChange()
    },
    handleGridItems(items, widget) {
      for (const item of items) {
        const itemId = widget ? widget.id : item.id
        item.id = itemId
        const itemEl = item.el
        const itemElContent = itemEl.querySelector('.grid-stack-item-content')
        const mountPoint = document.createElement('div')
        mountPoint.style = 'height: calc(100% - 4px);box-sizing:border-box;margin:2px'
        mountPoint.id = `grid-item-${itemId}`
        itemElContent.appendChild(mountPoint)

        // 添加到gridItems数组
        this.gridItems.push({
          id: itemId,
          widget: widget ?? this.widget.cols.find(col => itemId === col.id),
          remove: () => {
            this.grid.removeWidget(itemEl)
          },
        })
        this.isLoad = false
        this.isLoaded = true
      }
    },
  },
}
</script>

<style lang="scss" scoped>

.selected {
  outline: 2px solid var(--ep-color-primary) !important;
}

.grid-stack {
  background: rgba(249 250 251);
}

:deep(.grid-stack-item-content) {
  background-color: white;
  outline: 1px solid #cccccc;
}
</style>
